package cn.itlaobing.web.filter;


import cn.itlaobing.web.Constants;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Description:
 * @Author: WangDong
 * @Date: 2017/11/3 19:48
 */
@WebFilter("/*")
public class AuthentticationFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest req=null;
        HttpServletResponse resp=null;
        if(servletRequest instanceof HttpServletRequest){
            req=(HttpServletRequest)servletRequest;
        }
        if(servletResponse instanceof HttpServletResponse){
            resp=(HttpServletResponse)servletResponse;
        }
        req.setCharacterEncoding("utf-8");
        //取得当前请求地址
        String requestUrl=req.getRequestURI();
        System.out.println(requestUrl+">>>>>>>>>>>>");
        if("/auth/signin".equals(requestUrl) || "/index.jsp".equals(requestUrl) || requestUrl.startsWith("/assets") ){
            filterChain.doFilter(req,resp);
        }else{
            //判断是否登录
            if(req.getSession().getAttribute("USER_IN_SESSIONSCOPE")==null){
                req.getSession().setAttribute("MSG","请先登录后再操作");
                resp.sendRedirect(req.getContextPath()+"/index.jsp");
                return;
            }else{
                //如果登录了放行
                filterChain.doFilter(req,resp);
            }

        }

    }

    @Override
    public void destroy() {

    }
}
